#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: ileler@qq.com
import re
from shutil import move
from urllib import parse
from pathlib import Path

class REMatcher(object):
    def __init__(self, matchstring):
        self.matchstring = matchstring

    def match(self,regexp):
        self.rematch = re.match(regexp, self.matchstring)
        return bool(self.rematch)

    def group(self,i):
        return self.rematch.group(i)

def get_path(name):
    try:
        files = Path('./').glob('**/%s.md' % name)
        for file in files:
            return str(file)
    except:
        pass
    return None

prefix = '##### '
filepath = './README.md'
temppath = filepath + '.tmp'
with open(filepath, 'r') as lines:
    with open(temppath, 'w') as file:
        for line in lines:
            m1 = REMatcher(line)
            if not m1.match(r'%s(.*)' % prefix):
                file.write(line)
                continue
            name = m1.group(1)
            m2 = REMatcher(name)
            if m2.match(r'\[(.*)\]\((.*)\)'):
                name = m2.group(1)
            path = get_path(name)
            file.write(('%s[%s](%s)\n' % (prefix, name, parse.quote(path))) if path else line)
move(temppath, filepath)
